package top.lywivan.reggie.common;

import top.lywivan.reggie.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
@Component
public class GlobalExceptionHandler {
    /**
     * 处理用户名重复的异常
     * @param e 抛出该异常表示用户名重复
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R catchDupException(SQLIntegrityConstraintViolationException e){
        log.warn("发生了sql异常：{}",e.getMessage());
        String message = e.getMessage();
        if (message.contains("Duplicate entry")){
            String name = message.split(" ")[2];
            return R.error(name+"已存在");
        }else {
            return R.error("未知异常");
        }
    }

    /**
     * 删除分类时，有关联内容，则会抛出该异常
     * @param e 抛出的异常信息
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public R catchBusinessException(BusinessException e){
        log.warn("发生了关联导致无法删除分类的异常:{}",e.getMessage());
        return R.error(e.getMessage());
    }
}
